<template>
  <div class="header" :class="{ header_show: headerShow, shadow: headerShowActive }">
    <div class="header_container">
      <div class="header_content">
        <div class="flex_between">
          <div class="flex_start">
            <div class="logo">
              <router-link to="/">
                <img src="../../public/logo.png" />
                <span class="name">云学考学习考试系统</span>
              </router-link>
            </div>
            <div class="menu-wrapper">
              <div class="menu-item" v-for="(nav, index) in navList" :key="index">
                <h2 class="menu-item-link">
                  <router-link :to="nav.path" :class="currentModel == nav.path? 'active':''">
                    <span>{{ nav.name }}</span>
                  </router-link>
                </h2>
              </div>
            </div>
          </div>
          <div class="searchBar">
            <div style="margin-right: 30px">
              <a-popover trigger="focus">
                <template #content>
                  <a-spin :spinning="loadingKeyword">
                    <div style="width: 280px;">
                      <template v-if="mySearchHistoryList?.length >0">
                        <div class="searchTitle">我的搜索历史</div>
                        <div style="width:100%;display: flex;flex-wrap: wrap">
                          <a-tag style="margin: 5px 10px 5px 0 "
                                 v-for="(item,index) in mySearchHistoryList"
                                 :key="index"
                                 @click="handleCommonSearch(item)">{{ item }}
                          </a-tag>
                        </div>
                        <a-divider />
                      </template>
                      <div class="searchTitle">云学考热搜</div>
                      <div style="width:100%;display: flex;flex-wrap: wrap"
                           v-if="hotSearchList?.length >0">
                        <a-tag style="margin: 5px 10px 5px 0 " v-for="(item,index) in hotSearchList"
                               :key="index"
                               @click="handleCommonSearch(item.keyword)">{{ item.keyword }}
                        </a-tag>
                      </div>
                      <EmptyData v-else />
                    </div>
                  </a-spin>
                </template>
                <a-input v-model:value="pageInfo.keyword" style="width: 200px"
                         placeholder="搜索"
                         @keyup.enter="handleSearch"
                         @focus="handleFocus">
                  <template #suffix>
                    <search-outlined style="color: rgba(0, 0, 0, 0.45)" />
                  </template>
                </a-input>
              </a-popover>
            </div>
            <div style="display: flex">
              <a-space warp v-if="!loginState">
                <a-button size="small" type="primary" danger @click="toLogin">登录</a-button>
                <a-button size="small" danger @click="toRegister">注册</a-button>
              </a-space>
              <template v-else>
                <a-dropdown>
                  <a class="ant-dropdown-link" @click.prevent>
                    <div style="display: flex;">
                      <div style="margin: 0 10px">
                        <a-avatar :size="40" :src="getFile(userInfo.avatar)" />
                      </div>
                      <template v-if="userInfo?.realname">
                        <div class="realname" v-if="userInfo?.realname.length < 4">
                          {{ userInfo?.realname }}
                        </div>
                        <div class="realname" v-else>{{ userInfo?.realname?.substring(0, 4) }}</div>
                      </template>
                    </div>
                  </a>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <a-popconfirm title="确定退出登录吗？" ok-text="退出" cancel-text="取消"
                                      @confirm="logout">
                          <a href="#">
                            <LogoutOutlined style="margin-right: 5px" />
                            退出登录</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <a-modal v-model:open="showSearch" title="搜索结果" width="800px" :footer="null"
             destroy-on-close>
      <SearchList :items="searchItems" :loading="loading" @changeSearchType="changeSearchType" />
      <Pagination :pageNo="pageInfo.pageNo" :pageSize="pageInfo.pageSize" :total="total"
                  @change-page="changePage" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { computed, ref, watch } from "vue";
import { useWebStore } from "@/store";
import { useRouter } from "vue-router";
import { LogoutOutlined, SearchOutlined } from "@ant-design/icons-vue";
import EmptyData from "@/components/public/EmptyData.vue";
import Pagination from "@/components/Pagination.vue";
import { addKeyword, getSearchList, hotSearchCount, mySearchHistory } from "@/api/search";
import SearchList from "@/components/search/SearchList.vue";

const total = ref<number>(0);
const hotSearchList = ref<any>([]);
const mySearchHistoryList = ref<any>([]);
const loadingKeyword = ref<boolean>(false);
const showSearch = ref<any>(false);
const searchItems = ref<any>({});
const router = useRouter();
const webStore = useWebStore();
const headerShowActive = computed(() => webStore.headerShadowActive);
const headerShow = computed(() => webStore.headerShow);
const currentModel = computed(() => webStore.currentModel);
const loginState = computed(() => webStore.getLoginState);
const navList = ref<any>([
  {
    "path": "/course",
    "name": "课程学习"
  },
  {
    "path": "/exam",
    "name": "在线考试"
  },
  {
    "path": "/practice",
    "name": "题库练习"
  },
  {
    "path": "/news",
    "name": "新闻资讯"
  },
  {
    "path": "/userCenter",
    "name": "个人中心"
  },
  {
    "path": "/chatGPT",
    "name": "智能助手"
  }
]);
const userInfo = ref<any>({});

const loading = ref<boolean>(false);

const pageInfo = ref<{
  pageNo: number;
  pageSize: number;
  keyword: string;
  searchType: string;
}>({
  // 当前页码
  pageNo: 1,
  // 当前每页显示多少条数据
  pageSize: 30,
  keyword: "",
  searchType: ""
});

watch(loginState, async (newValue, oldValue) => {
  if (!newValue) {
    userInfo.value = {};
  } else {
    userInfo.value = webStore.getUserInfo;
  }
}, { immediate: true, deep: true });

function toLogin() {
  router.push({ path: `/login` });
}

function toRegister() {
  router.push({ path: `/register` });
}

async function logout() {
  webStore.userLogout();
  await router.push("/login");
}

async function handleCommonSearch(keyword) {
  pageInfo.value.keyword = keyword;
  pageInfo.value.pageNo = 1;
  pageInfo.value.searchType = "";
  showSearch.value = true;
  await getSearchItems();
}

async function handleSearch() {
  if (!pageInfo.value.keyword) {
    return;
  }
  pageInfo.value.pageNo = 1;
  pageInfo.value.searchType = "";
  showSearch.value = true;
  await getSearchItems();
  addKeyword(pageInfo.value.keyword);
}

async function getSearchItems() {
  loading.value = true;
  try {
    const data: any = await getSearchList(pageInfo.value);
    searchItems.value = data.result?.groupBy;
    const newHtml = `<span style="color: red">${pageInfo.value.keyword}</span>`;
    for (let prop in searchItems.value) {
      const itemList: any = searchItems.value[prop];
      if (itemList?.length > 0) {
        itemList.forEach((item: any) => {
          item.title = item.title.replace(pageInfo.value.keyword, newHtml);
        });
      }
    }

    total.value = data.result?.pageList?.total;
  } finally {
    loading.value = false;
  }
}

async function handleFocus() {
  loadingKeyword.value = true;
  try {
    const hotData: any = await hotSearchCount(5);
    hotSearchList.value = hotData.result;
    const historyData: any = await mySearchHistory();
    mySearchHistoryList.value = historyData.result;
  } finally {
    loadingKeyword.value = false;
  }
}

function changePage(pageNo) {
  pageInfo.value.pageNo = pageNo;
  getSearchItems();
}

function changeSearchType(type) {
  pageInfo.value.pageNo = 1;
  pageInfo.value.searchType = type;
  getSearchItems();
}

</script>
<style lang="less" scoped>
@nav_active_color: #fe9d38;

.ant-divider-horizontal {
  margin: 8px 0;
}

h2 {
  margin: 0;
}

.header_show {
  transform: translateY(-62px);
}

.a_text_dark {
  color: rgba(0, 0, 0, .8);
}

.header {
  width: 100%;
  height: 60px;
  padding: 0 10px;
  background-color: #2d68ea;
  box-shadow: none;
  color: #FFF;

  position: fixed;
  z-index: 999;
  transition: transform .2s ease;

  //color: rgba(255, 255, 255, 1) !important;
  //transition: all 0.3s ease;
  .header_container {
    height: 100%;
  }
}

.shadow {
  background-color: rgba(255, 255, 255, .7);
  backdrop-filter: blur(8px);
  box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.1);
}

.header_content {
  height: 100%;
  margin: 0 auto;

  .logo {
    display: flex;
    align-items: center;

    .name {
      font-weight: 700;
      margin-left: 5px;
      color: #FFF;
      font-size: 20px;
    }

    img {
      width: 50px;
      height: 45px;
      vertical-align: middle;
    }
  }
}

.menu-wrapper {
  display: flex;
  flex-direction: row;
  list-style: none;
  -ms-flex-align: center;
  align-items: center;
  padding: 0;
  margin: 0 0 0 100px;
  position: relative;

  .menu-item {
    flex-shrink: 0;
  }

  > .menu-item + .menu-item {
    margin-left: 50px;
  }

  .menu-item-link {
    color: #FFF;
    font-weight: 400;
    font-size: 16px;
    line-height: 45px;
    cursor: pointer;
    position: relative;
  }
}

a {
  display: inline-block;
  color: #FFF;
  transition: color .3s;
}

a:hover {
  color: #fe9d38;
}

.active {
  color: @nav_active_color !important;
  font-weight: 600;

  span:after {
    content: "";
    display: block;
    height: 2px;
    position: absolute;
    width: 26px;
    left: calc(50% - 13px);
    bottom: 2px;
    background-color: @nav_active_color;
  }
}

.nav_text_white {
  color: rgba(255, 255, 255, 1);
}

.nav_text_dark {
  color: rgba(0, 0, 0, .8);
}

@media only screen and (max-width: 991px) {
  .header_content {
  }
}

.realname {
  margin-left: 10px;
  color: #FFF;
  font-size: 14px;
}

.flex_start {
  display: flex;
  justify-content: flex-start;;
}

.flex_between {
  display: flex;
  justify-content: space-between;
}

.searchBar {
  margin-right: 20px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.searchTitle {
  font-size: 14px;
  color: red;
  margin-bottom: 10px;
}
</style>
